#include "GraphicsGrid.h"
#include "GridModel.h"

#include <QPainter>
#include <QtMath>
#include <QtGlobal>
#include <QStyleOptionGraphicsItem>

#define DEBUG
#ifdef DEBUG
# include <QDebug>
#endif

namespace LeGraphicsView
{

    GraphicsGrid::GraphicsGrid():
        m_model(nullptr)
    {
        setGridColor(Qt::gray);
    }

    GraphicsGrid::~GraphicsGrid()
    {

    }

    void GraphicsGrid::setGridColor(const QColor &color)
    {
        m_color = color;
    }

    QColor GraphicsGrid::gridColor() const
    {
        return m_color;
    }

    void GraphicsGrid::paint(QPainter *painter, const QRectF &exposedRect)
    {
        if (m_model == nullptr)
        {
            return;
        }

        update();

        painter->save();
        painter->setClipRect(exposedRect);
        painter->setPen(QPen(m_color, 0, Qt::SolidLine));
        painter->drawLines(m_gridLines.data(), m_gridLines.count());
        painter->drawPoints(m_gridPoints.data(), m_gridPoints.count());
        painter->restore();
    }

    void GraphicsGrid::update()
    {
        auto xValues = m_model->majorXValues();
        auto yValues = m_model->majorYValues();

        m_gridLines.resize(xValues.count() + yValues.count());
        for (int i = 0; i < xValues.count(); i++)
        {
            m_gridLines[i] = QLineF(xValues[i], m_model->sceneRect().top(),
                                    xValues[i], m_model->sceneRect().bottom());
        }

        int offset = xValues.count();
        for (int i = 0; i < yValues.count(); i++)
        {
            m_gridLines[offset+i] = QLineF(m_model->sceneRect().left(), yValues[i],
                                           m_model->sceneRect().right(), yValues[i]);
        }

        xValues = m_model->minorXValues();
        yValues = m_model->minorYValues();
        m_gridPoints.resize(xValues.count() * yValues.count());
        for (int i = 0; i < xValues.count(); i++)
        {
            for (int j = 0; j < yValues.count(); j++)
            {
                m_gridPoints[i * yValues.count() + j] = QPointF(xValues[i],
                                                                yValues[j]);
            }
        }
    }

    void GraphicsGrid::setGridModel(GridModel *model)
    {
        m_model = model;
    }

}
